﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RN.ERP.DAL.Context;
using RN.ERP.Entity.Authority;
using Fly.FlyCommon;
using System.Data.Entity;
using RN.ERP.Entity.ZBDLRY;
using Fly.Log;
using RN.ERP.Entity;
using RN.ERP.DAL.ZbdlryDAL;
using Newtonsoft.Json;

namespace RN.ERP.BLL.ZBDLRY
{
    public class AuthorityBLL : BaseAuthorityBLL
    {
        private ZBDL_Context dbContext
        {
            get
            {
                return (ZBDL_Context)base.baseContext;
            }
        }
        public AuthorityBLL()
        {
            base.baseContext = new ZBDL_Context();
        }

        #region 角色管理 刘焕
        /// <summary>
        /// 获取角色列表
        /// </summary>
        /// <param name="title">名称</param>
        /// <param name="code">编号</param>
        /// <param name="areacode">地区编号</param>
        /// <param name="description">描述</param>
        /// <returns></returns>
        public override List<DTO.T_Sys_Roles> GetRoles(string title, string code, string areacode, string description)
        {
            var query = from a in dbContext.SysRoles
                        where a.IsDel == false
                        select a;

            if (!string.IsNullOrEmpty(title))
            {
                query = query.Where(r => r.Title.Contains(title));
            }
            if (!string.IsNullOrEmpty(code))
            {
                query = query.Where(r => r.Code.Contains(code));
            }
            if (!string.IsNullOrEmpty(areacode))
            {
                query = query.Where(r => r.AreaCode.Contains(areacode));
            }
            if (!string.IsNullOrEmpty(description))
            {
                query = query.Where(r => r.Description.Contains(description));
            }

            areacode = System.Configuration.ConfigurationManager.AppSettings["Area"];
            if (!string.IsNullOrEmpty(areacode))
            {
                query = query.Where(r => r.AreaCode.Contains(areacode));
            }

            List<T_Sys_Roles> list = query.OrderBy(m => m.ID).ToList();
            List<DTO.T_Sys_Roles> lists = new List<DTO.T_Sys_Roles>();
            foreach (T_Sys_Roles item in list)
            {
                DTO.T_Sys_Roles role = new DTO.T_Sys_Roles();
                EntityHelper.ConvertEntity2OtherEntity(item, role);
                lists.Add(role);
            }
            return lists;
        }

        /// <summary>
        /// 根据角色GuID获取角色信息
        /// </summary>
        /// <param name="guid"></param>
        /// <returns></returns>
        public override DTO.T_Sys_Roles GetRoleByGuId(Guid guid)
        {
            T_Sys_Roles role = dbContext.SysRoles.Where(m => m.RoleGuid == guid).FirstOrDefault();
            DTO.T_Sys_Roles roles = new DTO.T_Sys_Roles();
            EntityHelper.ConvertEntity2OtherEntity(role, roles);
            return roles;
        }

        /// <summary>
        /// 添加角色
        /// </summary>
        /// <param name="role"></param>
        /// <returns></returns>
        public override DTO.OperationResult AddRole(DTO.T_Sys_Roles roleDTO)
        {
            T_Sys_Roles roles = new T_Sys_Roles();
            EntityHelper.ConvertEntity2OtherEntity(roleDTO, roles);
            DTO.OperationResult result = new DTO.OperationResult();
            try
            {
                dbContext.SysRoles.Add(roles);
                dbContext.SaveChanges();

                #region 添加操作日志
                DTO.UserPermission userLog = new DTO.UserPermission();
                string content = "添加角色信息！";
                string objectid = roles.RoleGuid.ToString();
                userLog.UserId = roleDTO.IsrtUseID != null ? roleDTO.IsrtUseID.ToString() : null;
                userLog.UserName = "";
                userLog.FunctionId = DTO.FunctionId.角色模块;
                userLog.FunctionType = DTO.FunctionType.添加;
                InsertUserLog(content, objectid, userLog);
                #endregion

                result.Result = true;
                result.ReturnValue = null;
                result.Message = "角色添加成功！";
            }
            catch (Exception ex)
            {
                result.Message = "角色添加失败！" + ex.Message;
                result.Result = false;
            }
            return result;
        }

        /// <summary>
        /// 修改角色信息
        /// </summary>
        /// <param name="roleDTO"></param>
        /// <returns></returns>
        public override DTO.OperationResult UpdateRole(DTO.T_Sys_Roles roles)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            result.Result = false;
            try
            {
                var role = dbContext.SysRoles.Where(r => r.RoleGuid == roles.RoleGuid).FirstOrDefault();
                if (role != null)
                {
                    role.Title = roles.Title;
                    role.Description = roles.Description;
                    role.Code = roles.Code;
                    role.AreaCode = roles.AreaCode;
                    role.GroupId = roles.GroupId;
                    role.IsDel = roles.IsDel;
                    dbContext.SaveChanges();

                    #region 添加操作日志
                    DTO.UserPermission userLog = new DTO.UserPermission();
                    string content = "修改角色信息！";
                    string objectid = role.RoleGuid.ToString();
                    userLog.UserId = roles.IsrtUseID != null ? roles.IsrtUseID.ToString() : null;
                    userLog.UserName = "";
                    userLog.FunctionId = DTO.FunctionId.角色模块;
                    userLog.FunctionType = DTO.FunctionType.修改;
                    InsertUserLog(content, objectid, userLog);
                    #endregion

                    result.Result = true;
                    result.ReturnValue = null;
                    result.Message = "角色修改成功！";
                }
            }
            catch (Exception ex)
            {
                result.Message = "角色修改失败！" + ex.Message;
            }
            return result;
        }

        /// <summary>
        /// 根据角色Guid获取人员信息(无用)
        /// </summary>
        /// <param name="roleGuid">角色Guid</param>
        /// <returns></returns>
        public override List<DTO.Sys_Users> GetUserListByRoleGuid(Guid roleGuid)
        {
            DbSet<T_Sys_Users_Zbdl> dbUser = dbContext.T_Sys_Users;
            DbSet<T_Sys_UserRole> dbUserRoles = dbContext.SysUserRoles;
            var query = from user in dbUser
                        join role in dbUserRoles on user.UserGuid equals role.UserGuid
                        where role.RoleGuid == roleGuid && role.IsDel == false
                        select new
                        {
                            user.UserGuid,
                            user.Name,
                            user.DeptName
                        };
            var list = query.ToList();
            List<DTO.Sys_Users> lists = new List<DTO.Sys_Users>();
            foreach (var item in list)
            {
                DTO.Sys_Users user = new DTO.Sys_Users();
                EntityHelper.ConvertEntity2OtherEntity(item, user);
                lists.Add(user);
            }
            return lists;
        }

        /// <summary>
        /// 根据角色Guid和用户Guid删除用户的角色(无用)
        /// </summary>
        /// <param name="roleGuid">角色Guid</param>
        /// <param name="userGuid">用户Guid</param>
        /// <returns></returns>
        public override DTO.OperationResult DeleteByUserRole(string roleGuid, string userGuid)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            try
            {
                Guid roleguid = Guid.Parse(roleGuid);
                Guid userguid = Guid.Parse(userGuid);
                var role = dbContext.SysUserRoles.Where(o => o.RoleGuid == roleguid && o.UserGuid == userguid).FirstOrDefault();
                role.IsDel = true;
                dbContext.SaveChanges();

                #region 添加操作日志
                DTO.UserPermission userLog = new DTO.UserPermission();
                string content = "删除用户角色信息！(逻辑删除：设置IsDel字段为：true)";
                string objectid = role.ID.ToString();
                userLog.UserId = new Guid().ToString();
                userLog.UserName = "";
                userLog.FunctionId = DTO.FunctionId.人员关联角色;
                userLog.FunctionType = DTO.FunctionType.删除;
                InsertUserLog(content, objectid, userLog);
                #endregion

                result.Result = true;
                result.ReturnValue = null;
                result.Message = "删除成功！";
            }
            catch (Exception ex)
            {
                result.Message = "删除失败！" + ex.Message;
                result.Result = false;
            }
            return result;
        }

        /// <summary>
        /// 判断人员是否有角色(无用)
        /// </summary>
        /// <param name="roleGuid"></param>
        /// <param name="userGuid"></param>
        /// <returns></returns>
        public override DTO.OperationResult GetUserRoleByUserRole(string roleGuid, string userGuid, string userID)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            try
            {
                Guid roleguid = Guid.Parse(roleGuid);
                Guid userguid = Guid.Parse(userGuid);
                var role = dbContext.SysUserRoles.Where(o => o.RoleGuid == roleguid && o.UserGuid == userguid).FirstOrDefault();
                if (role != null)
                {
                    if ((bool)role.IsDel && userID != null)
                    {
                        role.IsDel = false;
                        role.IsrtDate = DateTime.Now;
                        role.IsrtUseID = Guid.Parse(userID);
                        dbContext.SaveChanges();

                        #region 添加操作日志
                        DTO.UserPermission userLog = new DTO.UserPermission();
                        string content = "根据用户GUID和角色GUID获取记录！如已删除此记录，将重新添加此记录！(添加：设置IsDel字段为：false)";
                        string objectid = role.ID.ToString();
                        userLog.UserId = new Guid().ToString();
                        userLog.UserName = "";
                        userLog.FunctionId = DTO.FunctionId.人员关联角色;
                        userLog.FunctionType = DTO.FunctionType.添加;
                        InsertUserLog(content, objectid, userLog);
                        #endregion
                    }
                    result.Result = true;
                    result.ReturnValue = 1;
                    result.Message = "操作成功！";
                }
                else
                {
                    result.Result = true;
                    result.ReturnValue = 0;
                    result.Message = "操作成功！";
                }
            }
            catch (Exception ex)
            {
                result.Message = "操作失败！" + ex.Message;
                result.Result = false;
            }
            return result;
        }

        /// <summary>
        /// 根绝角色Guid获取人员角色表(无用)
        /// </summary>
        /// <param name="roleGuid"></param>
        /// <returns></returns>
        public override List<DTO.T_Sys_UserRole> GetUserRolesByRoleGuid(Guid roleGuid)
        {
            DbSet<T_Sys_UserRole> dbUserRoles = dbContext.SysUserRoles;
            var query = from userroles in dbUserRoles
                        where userroles.RoleGuid == roleGuid && userroles.IsDel == false
                        orderby userroles.IsrtDate descending
                        select userroles;
            List<T_Sys_UserRole> list = query.OrderByDescending(m => m.IsrtDate).ToList();
            List<DTO.T_Sys_UserRole> lists = new List<DTO.T_Sys_UserRole>();
            foreach (T_Sys_UserRole item in list)
            {
                DTO.T_Sys_UserRole user = new DTO.T_Sys_UserRole();
                EntityHelper.ConvertEntity2OtherEntity(item, user);
                lists.Add(user);
            }
            return lists;
        }

        /// <summary>
        /// 删除角色
        /// </summary>
        /// <param name="roleGuid"></param>
        /// <returns></returns>
        public override DTO.OperationResult DeleteRole(string roleGuid)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            result.Result = false;
            try
            {
                Guid roleguid = Guid.Empty;
                Guid.TryParse(roleGuid, out roleguid);
                var role = dbContext.SysRoles.Where(o => o.RoleGuid == roleguid).FirstOrDefault();
                if (role != null)
                {
                    role.IsDel = true;
                    dbContext.SaveChanges();

                    #region 添加操作日志
                    DTO.UserPermission userLog = new DTO.UserPermission();
                    string content = "删除角色信息！";
                    string objectid = role.RoleGuid.ToString();
                    userLog.UserId = new Guid().ToString();
                    userLog.UserName = "";
                    userLog.FunctionId = DTO.FunctionId.角色模块;
                    userLog.FunctionType = DTO.FunctionType.删除;
                    InsertUserLog(content, objectid, userLog);
                    #endregion

                    result.Result = true;
                    result.ReturnValue = null;
                    result.Message = "删除成功！";
                }
            }
            catch (Exception ex)
            {
                result.Message = "删除失败！" + ex.Message;
            }
            return result;
        }

        /// <summary>
        /// 根据用户guid获取用户角色（无用）
        /// </summary>
        /// <param name="userGuid"></param>
        /// <returns></returns>
        public override List<DTO.T_Sys_Roles> GetRolesByUserGuid(string userGuid)
        {
            Guid gUserGuid = Guid.Empty;
            Guid.TryParse(userGuid, out gUserGuid);
            var dbUserRoles = dbContext.SysUserRoles;
            var dbRoles = dbContext.SysRoles;
            var dbGroups = dbContext.SysRoleGroups;
            var query = from userRoles in dbUserRoles
                        join roles in dbRoles on userRoles.RoleGuid equals roles.RoleGuid
                        join groups in dbGroups on roles.GroupId equals groups.Id into jGroup
                        from roleGroups in jGroup.DefaultIfEmpty()
                        where userRoles.UserGuid == gUserGuid && roles.IsDel == false && userRoles.IsDel == false
                        select new DTO.T_Sys_Roles()
                        {
                            AreaCode = roles.AreaCode,
                            Code = roles.Code,
                            Description = roles.Description,
                            GroupId = roles.GroupId,
                            GroupCode = roleGroups.Code,
                            GroupTitle = roleGroups.Title,
                            ID = roles.ID,
                            IsDel = roles.IsDel,
                            IsrtDate = roles.IsrtDate,
                            IsrtUseID = roles.IsrtUseID,
                            RoleGuid = roles.RoleGuid,
                            Title = roles.Title
                        };
            return query.ToList();
        }

        #endregion 角色管理

        #region 分配功能权限 刘焕
        /// <summary>
        /// 给用户或角色分配功能，如果之前存在关联则修改数据
        /// </summary>
        /// <param name="funcDTO"></param>
        /// <returns></returns>
        public override DTO.OperationResult AddFuncPermission(DTO.T_Sys_FuncPermission funcDTO)
        {
            T_Sys_FuncPermission func = new T_Sys_FuncPermission();
            func = dbContext.SysFuncPermission.Where(r => r.FunctionGuid == funcDTO.FunctionGuid && r.ObjectGuid == funcDTO.ObjectGuid && r.Type ==
                funcDTO.Type && r.FuncType == funcDTO.FuncType && r.OperType == funcDTO.OperType).FirstOrDefault();
            if (func != null)//如果之前存在数据，则变更isdel
            {
                return UpdatePermission(funcDTO);
            }
            //不存在则新增一条数据
            DTO.OperationResult result = new DTO.OperationResult();
            try
            {
                func = new T_Sys_FuncPermission();
                EntityHelper.ConvertEntity2OtherEntity(funcDTO, func);

                dbContext.SysFuncPermission.Add(func);
                dbContext.SaveChanges();

                #region 添加操作日志
                DTO.UserPermission userLog = new DTO.UserPermission();
                string content = "给角色或人员添加功能！";
                string objectid = func.ID.ToString();
                userLog.UserId = funcDTO.IsrtUseID != null ? funcDTO.IsrtUseID.ToString() : null;
                userLog.UserName = "";
                userLog.FunctionId = DTO.FunctionId.角色关联功能;
                userLog.FunctionType = DTO.FunctionType.添加;
                InsertUserLog(content, objectid, userLog);
                #endregion

                result.Result = true;
                result.ReturnValue = null;
                result.Message = "添加成功！";
            }
            catch (Exception ex)
            {
                result.Message = "添加失败！" + ex.Message;
                result.Result = false;
            }
            return result;
        }

        /// <summary>
        /// 根据功能Guid和人员或角色Guid删除关联
        /// </summary>
        /// <param name="funcGuid">功能Guid</param>
        /// <param name="objGuid">人员或角色Guid</param>
        /// <returns></returns>
        public override DTO.OperationResult DelFuncPermission(Guid funcGuid, Guid objGuid)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            result.Result = false;
            try
            {
                var func = dbContext.SysFuncPermission.Where(f => f.FunctionGuid == funcGuid && f.ObjectGuid == objGuid && f.IsDel == false).ToList();
                if (func != null)
                {
                    foreach (var en in func)
                    {
                        en.IsDel = true;
                        dbContext.SaveChanges();

                        #region 添加操作日志
                        DTO.UserPermission userLog = new DTO.UserPermission();
                        string content = "删除关联";
                        string objectid = en.ID.ToString();
                        userLog.UserId = null;
                        userLog.UserName = "";
                        userLog.FunctionId = DTO.FunctionId.角色关联功能;
                        userLog.FunctionType = DTO.FunctionType.删除;
                        InsertUserLog(content, objectid, userLog);
                        #endregion

                        result.Result = true;
                        result.ReturnValue = null;
                        result.Message = "删除成功！";
                    }
                }
            }
            catch (Exception ex)
            {
                result.Message = "删除失败！" + ex.Message;
            }
            return result;
        }

        /// <summary>
        /// 根据角色(或人员)Guid获取权限
        /// </summary>
        /// <param name="guid"></param>
        /// <param name="type">角色(人员)Guid</param>
        /// <returns></returns>
        public override List<DTO.T_Sys_FuncPermission> GetFuncPermission(Guid guid, string appid)
        {
            List<T_Sys_FuncPermission> list;
            var query = from per in dbContext.SysFuncPermission
                        join func in dbContext.SysFunction on per.FunctionGuid equals func.FunctionGuid
                        where per.ObjectGuid == guid && func.AppID == appid && per.IsDel == false && func.IsDel == false
                        select per;
            list = query.ToList();
            List<DTO.T_Sys_FuncPermission> lists = new List<DTO.T_Sys_FuncPermission>();
            foreach (T_Sys_FuncPermission item in list)
            {
                DTO.T_Sys_FuncPermission role = new DTO.T_Sys_FuncPermission();
                EntityHelper.ConvertEntity2OtherEntity(item, role);
                lists.Add(role);
            }
            return lists;
        }

        /// <summary>
        /// 根据功能Guid和角色（人员）Guid判断是否添加该功能(无用)
        /// </summary>
        /// <param name="objGuid"></param>
        /// <param name="funcGuid"></param>
        /// <param name="userID"></param>
        /// <returns></returns>
        public override DTO.OperationResult GetFuncByFuncObj(string objGuid, string funcGuid, string userID)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            try
            {
                Guid objguid = Guid.Parse(objGuid);
                Guid funcguid = Guid.Parse(funcGuid);
                var func = dbContext.SysFuncPermission.Where(o => o.ObjectGuid == objguid && o.FunctionGuid == funcguid).FirstOrDefault();
                if (func != null)
                {
                    if ((bool)func.IsDel && userID != null)
                    {
                        func.IsDel = false;
                        func.IsrtDate = DateTime.Now;
                        func.IsrtUseID = Guid.Parse(userID);
                        dbContext.SaveChanges();

                        #region 添加操作日志
                        DTO.UserPermission userLog = new DTO.UserPermission();
                        string content = "根据角色Guid判断是否添加该功能!如果存在已删除记录将重新添加此记录！(添加：设置IsDel字段为：false)";
                        string objectid = func.ID.ToString();
                        userLog.UserId = new Guid().ToString();
                        userLog.UserName = "";
                        userLog.FunctionId = DTO.FunctionId.角色关联功能;
                        userLog.FunctionType = DTO.FunctionType.添加;
                        InsertUserLog(content, objectid, userLog);
                        #endregion
                    }
                    result.Result = true;
                    result.ReturnValue = 1;
                    result.Message = "操作成功！";
                }
                else
                {
                    result.Result = true;
                    result.ReturnValue = 0;
                    result.Message = "操作成功！";
                }
            }
            catch (Exception ex)
            {
                result.Message = "操作失败！" + ex.Message;
                result.Result = false;
            }
            return result;
        }

        /// <summary>
        /// 根据用户Guid和功能Guid 检测该用户是否存在此功能 --孙正滨(无用)
        /// </summary>
        /// <param name="userGuid">用户Guid</param>
        /// <param name="funcGuid">功能Guid</param>
        /// <returns></returns>
        public override DTO.OperationResult CheckFuncByUserGuid(string userGuid, string funcGuid)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            try
            {
                Guid objguid = Guid.Parse(userGuid);
                Guid funcguid = Guid.Parse(funcGuid);
                var func = dbContext.SysFuncPermission.Where(o => o.ObjectGuid == objguid && o.FunctionGuid == funcguid).FirstOrDefault();
                if (func != null)
                {
                    //func.OperType = 1;
                    dbContext.SaveChanges();

                    #region 添加操作日志
                    DTO.UserPermission userLog = new DTO.UserPermission();
                    string content = "根据用户Guid和功能Guid 检测该用户是否存在此功能!如果存在就删除此记录！(逻辑删除：设置OperType字段为：1)";
                    string objectid = func.ID.ToString();
                    userLog.UserId = new Guid().ToString();
                    userLog.UserName = "";
                    userLog.FunctionId = DTO.FunctionId.人员关联功能;
                    userLog.FunctionType = DTO.FunctionType.删除;
                    InsertUserLog(content, objectid, userLog);
                    #endregion

                    result.Result = true;
                    result.ReturnValue = 1;
                    result.Message = "操作成功！";
                }
                else
                {
                    result.Result = true;
                    result.ReturnValue = 0;
                    result.Message = "操作成功！";
                }
            }
            catch (Exception ex)
            {
                result.Message = "操作失败！" + ex.Message;
                result.Result = false;
            }
            return result;
        }

        /// <summary>
        /// 根据角色(人员)Guid获取权限 --孙正滨(无用)
        /// </summary>
        /// <param name="guid"></param>
        /// <param name="type">人员Guid</param>
        /// <returns></returns>
        public override List<DTO.T_Sys_FuncPermission> GetFuncListByUserGuid(Guid guid)
        {
            //List<T_Sys_FuncPermission> list;
            //list = dbContext.SysFuncPermission.Where(f => f.ObjectGuid == guid && f.OperType == 0).ToList();
            //List<DTO.T_Sys_FuncPermission> lists = new List<DTO.T_Sys_FuncPermission>();
            //foreach (T_Sys_FuncPermission item in list)
            //{
            //    DTO.T_Sys_FuncPermission role = new DTO.T_Sys_FuncPermission();
            //    EntityHelper.ConvertEntity2OtherEntity(item, role);
            //    lists.Add(role);
            //}
            //return lists;
            return null;
        }

        /// <summary>
        /// 根据人员Guid判断是否添加该功能 -- 孙正滨(无用)
        /// </summary>
        /// <param name="objGuid">用户GUID</param>
        /// <param name="funcGuid">功能GUID</param>
        /// <param name="userID">添加人GUID</param>
        /// <returns></returns>
        public override DTO.OperationResult ChechFuncByFuncObj(string objGuid, string funcGuid, string userID)
        {
            //DTO.OperationResult result = new DTO.OperationResult();
            //try
            //{
            //    Guid objguid = Guid.Parse(objGuid);
            //    Guid funcguid = Guid.Parse(funcGuid);
            //    var func = dbContext.SysFuncPermission.Where(o => o.ObjectGuid == objguid && o.FunctionGuid == funcguid).FirstOrDefault();
            //    if (func != null)
            //    {
            //        if (func.OperType == 1 && userID != null)
            //        {
            //            func.OperType = 0;
            //            func.IsrtDate = DateTime.Now;
            //            func.IsrtUseID = Guid.Parse(userID);
            //            dbContext.SaveChanges();

            //            #region 添加操作日志
            //            DTO.UserPermission userLog = new DTO.UserPermission();
            //            string content = " 根据人员Guid判断是否添加该功能!如果存在已删除记录将重新添加此记录！(添加：设置OperType字段为：0)";
            //            string objectid = func.ID.ToString();
            //            userLog.UserId = new Guid().ToString();
            //            userLog.UserName = "";
            //            userLog.FunctionId = DTO.FunctionId.人员关联功能;
            //            userLog.FunctionType = DTO.FunctionType.添加;
            //            InsertUserLog(content, objectid, userLog);
            //            #endregion
            //        }
            //        result.Result = true;
            //        result.ReturnValue = 1;
            //        result.Message = "操作成功！";
            //    }
            //    else
            //    {
            //        result.Result = true;
            //        result.ReturnValue = 0;
            //        result.Message = "操作成功！";
            //    }
            //}
            //catch (Exception ex)
            //{
            //    result.Message = "操作失败！" + ex.Message;
            //    result.Result = false;
            //}
            //return result;
            return null;
        }
        #endregion

        #region 添加日志
        /// <summary>
        /// 插入记录
        /// </summary>
        /// <param name="content"></param>
        /// <param name="objectid"></param>
        /// <param name="user"></param>
        private void InsertUserLog(string content, string objectid, DTO.UserPermission user)
        {
            UserLogManager.Log(new User_Log()
            {
                Content = content, //操作说明
                ObjectId = objectid, //记录主键
                IsrtUser = user.UserId, //操作人人ID
                IsrtUserName = user.UserName, //操作人姓名
                IsrtUserArea = "02", //操作人地区号
                FunctionId = ((int)user.FunctionId).ToString(), //操作功能编号
                FunctionType = ((int)user.FunctionType).ToString(), //操作功能编号
                AppId = "99" //项目编号
            }); ;
        }
        #endregion

        #region UC控件调用
        public override List<DTO.tb_Emp_TitleType> GetPsnQualLevelByType(int nid)
        {
            List<int> titleclass = (from a in dbContext.tb_Emp_TitleClass
                                    where a.ClassID == nid && a.Token == "JiBie"
                                    select a.NID).ToList();

            var level = (from b in dbContext.tb_Emp_TitleType
                         where titleclass.Contains(b.NID)
                         select b).ToList();
            //if (level == null||level.Count==0)
            //{
            //    level = dbContext.tb_Emp_TitleClass.Where(m => m.ClassID == -1 && m.Token == "JiBie").ToList();
            //}

            List<DTO.tb_Emp_TitleType> ret = new List<DTO.tb_Emp_TitleType>();
            foreach (tb_Emp_TitleType_Zbdl item in level)
            {
                DTO.tb_Emp_TitleType lv = new DTO.tb_Emp_TitleType();
                Fly.FlyCommon.EntityHelper.ConvertEntity2OtherEntity(item, lv);
                ret.Add(lv);
            }
            return ret;
        }
        #endregion UC控件调用

        #region 功能管理 蓝立明
        /// <summary>
        /// 功能更新
        /// </summary>
        /// <returns></returns>
        public override DTO.OperationResult UpdateFunction(DTO.T_Sys_Function function)
        {
            DbSet<T_Sys_Function> dbFunction = dbContext.SysFunction;
            DTO.OperationResult result = new DTO.OperationResult();
            result.Message = "更新失败";
            result.Result = false;
            result.ReturnValue = 0;
            try
            {
                var ret = dbFunction.Where(m => m.FunctionGuid == function.FunctionGuid && m.IsDel == false).FirstOrDefault();
                if (ret == null)
                {
                    result.Message = "找不到功能记录（GUID=" + function.FunctionGuid + ")";
                }
                else
                {
                    if (!IsExistFunc(function.Code, ret.ParenGuid, ret.FunctionGuid, ret.AppID))
                    {
                        //int before = function.Url.LastIndexOf('/');
                        //int after = function.Url.LastIndexOf('.');
                        //string url = function.Url.Substring(0, before + 1);
                        //string ext = "";
                        //if (after != -1)
                        //{
                        //    ext = function.Url.Substring(after);
                        //}
                        //function.Url = url + function.Code + ext;

                        ret.Code = function.Code;
                        ret.Title = function.Title;
                        ret.DESCRIPTION = function.DESCRIPTION;
                        //ret.AppID = function.AppID;
                        ret.Url = function.Url;
                        //ret.IsMenu = function.IsMenu;
                        //ret.ParenGuid = function.ParenGuid;
                        //ret.RootGuid = function.RootGuid;
                        dbContext.SaveChanges();

                        #region 添加操作日志
                        DTO.UserPermission userLog = new DTO.UserPermission();
                        string content = "修改功能！";
                        string objectid = ret.FunctionGuid.ToString();
                        userLog.UserId = function.IsrtUseID != null ? function.IsrtUseID.ToString() : null;
                        userLog.UserName = "";
                        userLog.FunctionId = DTO.FunctionId.功能模块;
                        userLog.FunctionType = DTO.FunctionType.修改;
                        InsertUserLog(content, objectid, userLog);
                        #endregion

                        result.Message = "更新成功";
                        result.ReturnValue = 1;
                        result.Result = true;
                    }
                    else
                    {
                        result.Message = "功能编号已存在";
                    }
                }
            }
            catch (Exception ex)
            {
                result.Message = "更新失败" + ex.Message;
            }
            return result;
        }
        /// <summary>
        /// 获取功能列表
        /// </summary>
        /// <param name="code">编号</param>
        /// <param name="title">名称</param>
        /// <param name="appID">项目ID</param>
        /// <param name="parentGuid">父节点</param>
        /// <param name="rootGuid">根节点</param>
        /// <param name="isMenu">是否菜单</param>
        /// <param name="isDel">是否删除</param>
        /// <returns></returns>
        public override IList<DTO.T_Sys_Function> GetFunctionList(DTO.FuncQueryCondition condition)
        {
            DbSet<T_Sys_Function> dbFunction = dbContext.SysFunction;
            var query =
               from Function in dbFunction
               select Function;
            if (!String.IsNullOrEmpty(condition.Code))
            {
                query = query.Where(o => o.Code.Contains(condition.Code));
            }
            if (!String.IsNullOrEmpty(condition.Title))
            {
                query = query.Where(o => o.Title.Contains(condition.Title));
            }
            if (!String.IsNullOrEmpty(condition.AppID))
            {
                query = query.Where(o => o.AppID == condition.AppID);
            }
            if (condition.ParentGuid != null)
            {
                query = query.Where(o => o.ParenGuid == condition.ParentGuid);
            }
            if (condition.RootGuid != null)
            {
                query = query.Where(o => o.RootGuid == condition.RootGuid);
            }
            if (condition.IsMenu != null)
            {
                query = query.Where(o => o.IsMenu == condition.IsMenu);
            }
            if (condition.IsDel != null)
            {
                query = query.Where(o => o.IsDel == condition.IsDel);
            }
            IList<T_Sys_Function> funclist = query.OrderBy(m => m.SortIndex).ToList();
            IList<DTO.T_Sys_Function> ret = new List<DTO.T_Sys_Function>();
            foreach (T_Sys_Function item in funclist)
            {
                DTO.T_Sys_Function func = new DTO.T_Sys_Function();
                Fly.FlyCommon.EntityHelper.ConvertEntity2OtherEntity(item, func);
                ret.Add(func);
            }

            return ret.ToList();
        }

        /// <summary>
        /// 功能删除
        /// </summary>
        /// <returns></returns>
        public override DTO.OperationResult DeleteFunction(Guid funcGuid)
        {
            DbSet<T_Sys_Function> dbFunction = dbContext.SysFunction;
            DTO.OperationResult result = new DTO.OperationResult();
            result.Message = "删除失败";
            result.Result = false;
            result.ReturnValue = 0;
            try
            {
                var role = dbFunction.Where(o => o.FunctionGuid == funcGuid).FirstOrDefault();
                role.IsDel = true;
                dbContext.SaveChanges();

                #region 添加操作日志
                DTO.UserPermission userLog = new DTO.UserPermission();
                string content = "删除功能！";
                string objectid = role.FunctionGuid.ToString();
                userLog.UserId = new Guid().ToString();
                userLog.UserName = "";
                userLog.FunctionId = DTO.FunctionId.功能模块;
                userLog.FunctionType = DTO.FunctionType.删除;
                InsertUserLog(content, objectid, userLog);
                #endregion

                result.Message = "删除成功";
                result.Result = true;
                result.ReturnValue = 1;
            }
            catch (Exception ex)
            {
                result.Message = "删除失败" + ex.Message;
            }
            return result;
        }

        public override DTO.OperationResult AddFunction(DTO.T_Sys_Function function)
        {
            //DbSet<T_Sys_Function> dbFunction = dbContext.SysFunction;
            DTO.OperationResult result = new DTO.OperationResult();
            result.Message = "添加失败";
            result.Result = false;
            result.ReturnValue = 0;
            try
            {
                if (!IsExistFunc(function.Code, function.ParenGuid, function.FunctionGuid, function.AppID))
                {
                    //int before = function.Url.LastIndexOf('/');
                    //int after = function.Url.LastIndexOf('.');
                    //string url = function.Url.Substring(0, before + 1);
                    //string ext = "";
                    //if (after != -1)
                    //{
                    //    ext = function.Url.Substring(after);
                    //}
                    //function.Url = url + function.Code + ext;

                    var funcs = from fu in dbContext.SysFunction
                                where fu.ParenGuid == function.ParenGuid && fu.IsDel == false
                                && fu.AppID == function.AppID
                                orderby fu.SortIndex descending
                                select fu.SortIndex;
                    if (funcs.FirstOrDefault() != null)
                    {
                        function.SortIndex = funcs.FirstOrDefault() + 1;
                    }
                    else
                    {
                        function.SortIndex = 1;
                    }

                    T_Sys_Function func = new T_Sys_Function();
                    Fly.FlyCommon.EntityHelper.ConvertEntity2OtherEntity(function, func);
                    dbContext.SysFunction.Add(func);

                    #region 添加操作日志
                    DTO.UserPermission userLog = new DTO.UserPermission();
                    string content = "添加功能！";
                    string objectid = func.FunctionGuid.ToString();
                    userLog.UserId = function.IsrtUseID != null ? function.IsrtUseID.ToString() : null;
                    userLog.UserName = "";
                    userLog.FunctionId = DTO.FunctionId.功能模块;
                    userLog.FunctionType = DTO.FunctionType.添加;
                    InsertUserLog(content, objectid, userLog);
                    #endregion

                    dbContext.SaveChanges();
                    result.Message = "添加成功";
                    result.Result = true;
                    result.ReturnValue = 1;
                }
                else
                {
                    result.Message = "功能编号已存在";
                }
            }
            catch (Exception ex)
            {
                result.Message = "添加失败" + ex.Message;
            }
            return result;
        }

        public bool IsExistFunc(string code, Guid? parent, Guid funcguid, string appid)
        {
            if (parent == Guid.Empty)//父级
            {
                var func = from fu in dbContext.SysFunction
                           where (fu.ParenGuid == parent || fu.ParenGuid != funcguid) && fu.Code == code && fu.IsDel == false && fu.AppID == appid
                           select fu;
                return func.ToList().Count > 0;
            }
            else//父级节点和子节点的code可以相同，但不能与其他一样
            {
                var function = from func in dbContext.SysFunction
                               where func.Code == code && func.ParenGuid != parent && func.FunctionGuid != parent && func.IsDel == false && func.AppID == appid
                               select func;
                return function.ToList().Count > 0;
            }
        }

        public override DTO.T_Sys_Function GetFunctionByGuid(Guid funcGuid)
        {
            DbSet<T_Sys_Function> dbFunction = dbContext.SysFunction;
            DTO.T_Sys_Function result = new DTO.T_Sys_Function();
            var function = dbFunction.Where(o => o.FunctionGuid == funcGuid && o.IsDel == false).FirstOrDefault();
            if (function != null)
            {
                Fly.FlyCommon.EntityHelper.ConvertEntity2OtherEntity(function, result);
            }
            return result;
        }

        public override IList<DTO.T_Sys_Function> GetMenuList(Guid userGuid, string appID)
        {
            //DbSet<T_Sys_Function> dbFunction = dbContext.SysFunction;
            //DbSet<T_Sys_UserRole> dbUserRoles = dbContext.SysUserRoles;
            //DbSet<T_Sys_Roles> dbRoles = dbContext.SysRoles;
            //DbSet<T_Sys_FuncPermission> dbFuncRoles = dbContext.SysFuncPermission;
            //DbSet<T_Sys_Users_Zbdl> dbUser = dbContext.T_Sys_Users;
            ////获取用户下的角色,角色下的功能
            //var query = from user in dbContext.T_Sys_Users
            //            join userRoles in dbContext.SysUserRoles on user.UserGuid equals userRoles.UserGuid into userUserRoles
            //            from userUserRole in userUserRoles.DefaultIfEmpty()
            //            join role in dbContext.SysRoles on userUserRole.RoleGuid equals role.RoleGuid
            //            join funcRoles in dbContext.SysFuncPermission on userUserRole.RoleGuid equals funcRoles.ObjectGuid into userFuncRoles
            //            from userFuncRole in userFuncRoles.DefaultIfEmpty()
            //            from function in dbContext.SysFunction
            //            where user.UserGuid == userGuid && userFuncRole.Type == 0 && function.FunctionGuid == userFuncRole.FunctionGuid && function.IsDel == false && function.IsMenu == true && role.IsDel == false
            //            select new DTO.T_Sys_Function { FunctionGuid = function.FunctionGuid, Title = function.Title, DESCRIPTION = function.DESCRIPTION, Url = function.Url, RootGuid = function.RootGuid, ParenGuid = function.ParenGuid, AppID = function.AppID };

            ////获取用户的特有功能
            //int operType = 0;
            //var queryOper = from user in dbContext.T_Sys_Users
            //                join funcRoles in dbContext.SysFuncPermission on user.UserGuid equals funcRoles.ObjectGuid into userFuncRoles
            //                from userFuncRole in userFuncRoles.DefaultIfEmpty()
            //                from function in dbContext.SysFunction
            //                where userFuncRole.Type == 1 && function.FunctionGuid == userFuncRole.FunctionGuid && function.IsDel == false && function.IsMenu == true
            //                && userFuncRole.OperType == operType
            //                select new DTO.T_Sys_Function { FunctionGuid = function.FunctionGuid, Title = function.Title, DESCRIPTION = function.DESCRIPTION, Url = function.Url, RootGuid = function.RootGuid, ParenGuid = function.ParenGuid, AppID = function.AppID };
            //if (!String.IsNullOrEmpty(appID))
            //{
            //    query = query.Where(o => o.AppID == appID);
            //    queryOper = query.Where(o => o.AppID == appID);
            //}
            //IList<DTO.T_Sys_Function> funcRole = query.ToList();
            ////添加个体功能
            //operType = 0;
            //IList<DTO.T_Sys_Function> funcAdd = queryOper.ToList();
            //if (funcAdd.Count > 0)
            //{
            //    foreach (var item in funcAdd)
            //    {
            //        int cnt = -1;
            //        cnt = funcRole.Where(o => o.FunctionGuid == item.FunctionGuid).ToList().Count();
            //        if (cnt == 0)
            //        {
            //            funcRole.Add(item);
            //        }
            //    }
            //}
            ////删除个体功能
            //operType = 1;
            //IList<DTO.T_Sys_Function> funcMinus = queryOper.ToList();
            //if (funcMinus.Count > 0)
            //{
            //    foreach (var item in funcMinus)
            //    {
            //        int cnt = -1;
            //        cnt = funcRole.Where(o => o.FunctionGuid == item.FunctionGuid).ToList().Count();
            //        if (cnt > 0)
            //        {
            //            funcRole.Remove(item);
            //        }
            //    }
            //}
            //return funcRole.ToList();
            return null;
        }

        /// <summary>
        /// 功能添加控件(无用)
        /// </summary>
        /// <param name="conFuncDTO"></param>
        /// <returns></returns>
        public override DTO.OperationResult AddConFunction(DTO.T_Sys_ControlFunction conFuncDTO)
        {
            DbSet<T_Sys_ControlFunction> dbConFunction = dbContext.SysConFunction;
            T_Sys_ControlFunction conFunc = new T_Sys_ControlFunction();
            EntityHelper.ConvertEntity2OtherEntity(conFuncDTO, conFunc);
            DTO.OperationResult result = new DTO.OperationResult();
            result.Message = "添加失败";
            result.Result = false;
            result.ReturnValue = 0;
            try
            {
                var rec = dbConFunction.Where(o => o.CtrlGuid == conFunc.CtrlGuid && o.FunctionGuid == conFunc.FunctionGuid).FirstOrDefault();
                if (rec != null)
                {
                    result.Message = "该数据已存在";
                    result.Result = false;
                    result.ReturnValue = 2;
                }
                else
                {
                    dbConFunction.Add(conFunc);
                    dbContext.SaveChanges();

                    #region 添加操作日志
                    DTO.UserPermission userLog = new DTO.UserPermission();
                    string content = "为功能分配控件！";
                    string objectid = conFunc.ID.ToString();
                    userLog.UserId = new Guid().ToString();
                    userLog.UserName = "";
                    userLog.FunctionId = DTO.FunctionId.功能关联控件;
                    userLog.FunctionType = DTO.FunctionType.添加;
                    InsertUserLog(content, objectid, userLog);
                    #endregion

                    result.Result = true;
                    result.ReturnValue = 1;
                    result.Message = "添加成功！";
                }
            }
            catch (Exception ex)
            {
                result.Message = "添加失败！" + ex.Message;
            }
            return result;
        }
        // 获取功能控件列表(无用)
        public override IList<DTO.T_Sys_ControlFunction> GetConFunctionList(Guid funcGuid)
        {
            DbSet<T_Sys_ControlFunction> dbConFunction = dbContext.SysConFunction;
            DbSet<T_Sys_Function> dbFunction = dbContext.SysFunction;
            var query = from function in dbFunction
                        join conFunction in dbConFunction on function.FunctionGuid equals conFunction.FunctionGuid into funcConFuncs
                        from funcConFunc in funcConFuncs.DefaultIfEmpty()
                        where function.IsDel == false && funcConFunc.FunctionGuid == funcGuid
                        select funcConFunc;
            IList<T_Sys_ControlFunction> conFuncList = query.ToList();
            IList<DTO.T_Sys_ControlFunction> conFuncDTOList = new List<DTO.T_Sys_ControlFunction>();
            foreach (T_Sys_ControlFunction item in conFuncList)
            {
                DTO.T_Sys_ControlFunction conFuncDTO = new DTO.T_Sys_ControlFunction();
                EntityHelper.ConvertEntity2OtherEntity(item, conFuncDTO);
                conFuncDTOList.Add(conFuncDTO);
            }
            return conFuncDTOList;
        }

        //操作功能控件列表(无用)
        public override DTO.OperationResult OperateConFunction(Guid funcGuid, Guid conGuid, DTO.OperationType type)
        {
            DbSet<T_Sys_ControlFunction> dbConFunction = dbContext.SysConFunction;
            DTO.OperationResult result = new DTO.OperationResult();
            result.Message = "操作失败";
            result.Result = false;
            result.ReturnValue = 0;
            try
            {
                if (type == DTO.OperationType.Add)
                {
                    var conFunc = dbConFunction.Where(o => o.FunctionGuid == funcGuid && o.CtrlGuid == conGuid).FirstOrDefault();
                    if (conFunc != null)
                    {
                        conFunc.IsDel = false;
                        dbContext.SaveChanges();

                        #region 添加操作日志
                        DTO.UserPermission userLog = new DTO.UserPermission();
                        string content = "根据功能GUID和控件GUID获取记录是否已被删除！如记录已删除将重新添加此记录！(添加：设置IsDel字段为：flase)";
                        string objectid = conFunc.ID.ToString();
                        userLog.UserId = new Guid().ToString();
                        userLog.UserName = "";
                        userLog.FunctionId = DTO.FunctionId.功能关联控件;
                        userLog.FunctionType = DTO.FunctionType.添加;
                        InsertUserLog(content, objectid, userLog);
                        #endregion

                        result.Message = "记录恢复,添加成功";
                        result.Result = true;
                        result.ReturnValue = 1;
                    }
                }
                if (type == DTO.OperationType.Delete)
                {
                    var conFunc = dbConFunction.Where(o => o.FunctionGuid == funcGuid && o.CtrlGuid == conGuid).FirstOrDefault();
                    conFunc.IsDel = true;
                    dbContext.SaveChanges();

                    #region 添加操作日志
                    DTO.UserPermission userLog = new DTO.UserPermission();
                    string content = "根据功能GUID和控件GUID获取记录是否被删除！如没有被删除将删除此记录！(添加：设置IsDel字段为：true)";
                    string objectid = conFunc.ID.ToString();
                    userLog.UserId = new Guid().ToString();
                    userLog.UserName = "";
                    userLog.FunctionId = DTO.FunctionId.功能关联控件;
                    userLog.FunctionType = DTO.FunctionType.删除;
                    InsertUserLog(content, objectid, userLog);
                    #endregion

                    result.Message = "删除成功";
                    result.Result = true;
                    result.ReturnValue = 2;
                }
            }
            catch (Exception ex)
            {
                result.Message = "操作失败！" + ex.Message;
            }
            return result;
        }
        #endregion

        #region 用户角色管理
        /// <summary>
        /// 获取企业列表(绑定到下拉菜单)
        /// </summary>
        /// <param name="corpName">姓名</param>
        /// <param name="username">用户名</param>
        /// <returns></returns>
        public override List<DTO.T_Sys_Users> GetUserList(string corpName, string username)
        {
            var list = new AuthorityDAL().GetUserList(corpName, username);

            List<DTO.T_Sys_Users> lists = new List<DTO.T_Sys_Users>();

            DTO.T_Sys_Users user = null;
            foreach (var u in list)
            { 
                user=new  DTO.T_Sys_Users
                        {
                            ID = u.ID,
                            UserGuid = u.UserGuid,
                            UserName = u.UserName,
                            Name = u.Name,
                            RoleID = u.BGrade,
                            AreaCode = u.AreaCode
                        };
                lists.Add(user);
            }

            return lists;
        }

        /// <summary>
        /// 设置用户角色（通过关系表）
        /// </summary>
        /// <param name="userGuid"></param>
        /// <param name="roleNum">角色号码</param>
        /// <param name="roleArea">角色区域</param>
        /// <returns></returns>
        public override DTO.OperationResult SetUserRole(Guid userGuid, string roleNum, string roleArea)
        {
            DTO.OperationResult result = new DTO.OperationResult();

            T_Sys_Roles userRole = dbContext.SysRoles.Where(r => r.Code == roleNum && r.AreaCode == roleArea && r.IsDel == false).FirstOrDefault();
            if (userRole == null)
            {
                result.Message = "角色表中不存在此类型！";
                result.Result = false;
                return result;
            }

            bool updateUserSuccess = UpdateUserRole(userGuid, Convert.ToInt32(roleNum));
            if (!updateUserSuccess)
            {
                result.Message = "更新用户表角色出错！";
                result.Result = false;
                return result;
            }

            Guid roleGuid = userRole.RoleGuid;
            bool setUserRoleReSuccess = SetUserRoleRe(userGuid, roleGuid, roleNum, roleArea);
            if (!setUserRoleReSuccess)
            {
                result.Message = "更新用户角色关系表出错！";
                result.Result = false;
                return result;
            }

            result.Message = "更新成功！";
            result.Result = true;

            return result;
        }

        /// <summary>
        /// 更新用户表角色
        /// </summary>
        /// <param name="userGuid"></param>
        /// <param name="roleNum"></param>
        /// <returns></returns>
        private bool UpdateUserRole(Guid userGuid, int roleNum)
        {
            bool res = false;

            try
            {
                T_Sys_Users_Zbdl user = dbContext.T_Sys_Users.Where(u => u.UserGuid == userGuid).FirstOrDefault();
                if (user != null)
                {
                    user.bGrade = roleNum;
                    user.RoleID = roleNum;
                    dbContext.SaveChanges();
                    res = true;
                }
            }
            catch (Exception)
            {
                throw;
            }

            return res;
        }

        /// <summary>
        /// 设置角色关系表
        /// </summary>
        /// <param name="userGuid"></param>
        /// <param name="roleGuid"></param>
        /// <param name="roleNum"></param>
        /// <param name="roleArea"></param>
        /// <returns></returns>
        private bool SetUserRoleRe(Guid userGuid, Guid roleGuid, string roleNum, string roleArea)
        {
            bool res = false;

            try
            {
                T_Sys_UserRole userRole = dbContext.SysUserRoles.Where(r => r.UserGuid == userGuid && r.IsDel == false).FirstOrDefault();
                if (userRole == null)
                {
                    userRole = new T_Sys_UserRole();
                    userRole.UserGuid = userGuid;
                    userRole.RoleGuid = roleGuid;
                    userRole.IsrtDate = DateTime.Now;
                    userRole.IsDel = false;
                    dbContext.SysUserRoles.Add(userRole);
                    dbContext.SaveChanges();
                }
                else
                {
                    userRole.RoleGuid = roleGuid;
                    userRole.IsrtDate = DateTime.Now;
                    dbContext.SaveChanges();
                }
                res = true;
            }
            catch (Exception)
            {
                throw;
            }

            return res;
        }

        // 获取角色列表
        public override List<DTO.T_Sys_UserRole> GetUserRoles(Guid userGuid)
        {
            var query =
                from userroles in dbContext.SysUserRoles
                where userroles.UserGuid == userGuid && userroles.IsDel == false
                orderby userroles.IsrtDate descending
                select userroles;
            List<T_Sys_UserRole> list = query.ToList();
            List<DTO.T_Sys_UserRole> lists = new List<DTO.T_Sys_UserRole>();
            foreach (T_Sys_UserRole item in list)
            {
                DTO.T_Sys_UserRole role = new DTO.T_Sys_UserRole();
                EntityHelper.ConvertEntity2OtherEntity(item, role);
                lists.Add(role);
            }
            return lists;
        }

        // 获取用户角色列表
        public override List<DTO.T_Sys_UserRole> GetUserRolesList(Guid userGuid, Guid roleGuid)
        {
            var query =
                from userroles in dbContext.SysUserRoles
                where userroles.UserGuid == userGuid && userroles.RoleGuid == roleGuid
                orderby userroles.IsrtDate descending
                select userroles;
            List<T_Sys_UserRole> list = query.ToList();
            List<DTO.T_Sys_UserRole> lists = new List<DTO.T_Sys_UserRole>();
            foreach (T_Sys_UserRole item in list)
            {
                DTO.T_Sys_UserRole role = new DTO.T_Sys_UserRole();
                EntityHelper.ConvertEntity2OtherEntity(item, role);
                lists.Add(role);
            }
            return lists;
        }

        /// <summary>
        /// 根据用户角色ID获取用户角色信息
        /// </summary>
        /// <param name="id">用户角色ID</param>
        /// <returns></returns>
        public override DTO.T_Sys_UserRole GetUserRoleById(int id)
        {
            T_Sys_UserRole role = dbContext.SysUserRoles.Where(m => m.ID == id).FirstOrDefault();
            DTO.T_Sys_UserRole roles = new DTO.T_Sys_UserRole();
            EntityHelper.ConvertEntity2OtherEntity(role, roles);
            return roles;
        }

        /// <summary>
        /// 根据用户角色Guid获取用户角色信息
        /// </summary>
        /// <param name="guid">用户角色Guid</param>
        /// <returns></returns>
        public override DTO.T_Sys_UserRole GetUserRoleByGuId(Guid roleGuid)
        {
            T_Sys_UserRole role = dbContext.SysUserRoles.Where(m => m.RoleGuid == roleGuid).FirstOrDefault();
            DTO.T_Sys_UserRole roles = new DTO.T_Sys_UserRole();
            EntityHelper.ConvertEntity2OtherEntity(role, roles);
            return roles;
        }

        /// <summary>
        /// 给用户分配角色
        /// </summary>
        /// <param name="userGuid">用户GUID</param>
        /// <param name="roleGuid">角色GUID</param>
        /// <param name="userID">添加人GUID</param>
        /// <returns></returns>
        public override DTO.OperationResult AddUserRole(DTO.T_Sys_UserRole userRoleDTO)
        {
            T_Sys_UserRole userRoles = new T_Sys_UserRole();
            EntityHelper.ConvertEntity2OtherEntity(userRoleDTO, userRoles);
            DTO.OperationResult result = new DTO.OperationResult();
            try
            {
                dbContext.SysUserRoles.Add(userRoles);
                dbContext.SaveChanges();

                #region 添加操作日志
                DTO.UserPermission userLog = new DTO.UserPermission();
                string content = "给角色分配角色！";
                string objectid = userRoles.ID.ToString();
                userLog.UserId = userRoles.IsrtUseID.ToString();
                userLog.UserName = "";
                userLog.FunctionId = DTO.FunctionId.人员关联角色;
                userLog.FunctionType = DTO.FunctionType.添加;
                InsertUserLog(content, objectid, userLog);
                #endregion

                result.Result = true;
                result.ReturnValue = null;
                result.Message = "用户角色添加成功！";
            }
            catch (Exception ex)
            {
                result.Message = "用户角色添加失败！" + ex.Message;
                result.Result = false;
            }
            return result;
        }

        /// <summary>
        /// 修改用户角色信息
        /// </summary>
        /// <param name="id">用户角色信息ID</param>
        /// <param name="roleGuid">角色GUID</param>
        /// <param name="userID">添加人GUID</param>
        /// <returns></returns>
        public override DTO.OperationResult UpdateUserRole(DTO.T_Sys_UserRole userRoleDTO)
        {
            T_Sys_UserRole userRoles = new T_Sys_UserRole();
            EntityHelper.ConvertEntity2OtherEntity(userRoleDTO, userRoles);
            DTO.OperationResult result = new DTO.OperationResult();
            try
            {
                var role = dbContext.SysUserRoles.Find(userRoles.ID);
                if (role != null)
                {
                    role.RoleGuid = userRoles.RoleGuid;
                    role.UserGuid = userRoles.UserGuid;
                    role.IsrtUseID = userRoles.IsrtUseID;
                    dbContext.SaveChanges();

                    #region 添加操作日志
                    DTO.UserPermission userLog = new DTO.UserPermission();
                    string content = "修改用户角色！";
                    string objectid = userRoles.ID.ToString();
                    userLog.UserId = userRoles.IsrtUseID.ToString();
                    userLog.UserName = "";
                    userLog.FunctionId = DTO.FunctionId.人员关联角色;
                    userLog.FunctionType = DTO.FunctionType.修改;
                    InsertUserLog(content, objectid, userLog);
                    #endregion

                    result.Result = true;
                    result.ReturnValue = null;
                    result.Message = "用户角色修改成功！";
                }
            }
            catch (Exception ex)
            {
                result.Message = "用户角色修改失败！" + ex.Message;
                result.Result = false;
            }
            return result;
        }

        /// <summary>
        /// 删除用户角色
        /// </summary>
        /// <param name="roleID">角色ID或角色GUID</param>
        /// <param name="type">0:通过ID,1:通过Guid</param>
        /// <returns></returns>
        public override DTO.OperationResult DeleteUserRole(string roleGuid, string userGuid)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            try
            {
                Guid roleguid = Guid.Parse(roleGuid);
                Guid userguid = Guid.Parse(userGuid);
                DbSet<T_Sys_UserRole> dbUserRoles = dbContext.SysUserRoles;
                var role = dbUserRoles.Where(o => o.RoleGuid == roleguid && o.UserGuid == userguid).FirstOrDefault();
                role.IsDel = true;
                dbContext.SaveChanges();

                #region 添加操作日志
                DTO.UserPermission userLog = new DTO.UserPermission();
                string content = "根据用户GUID和角色GUID判断是否存在此记录！如存在进行删除！(逻辑删除：设置IsDel字段为：true)";
                string objectid = role.ID.ToString();
                userLog.UserId = role.IsrtUseID.ToString();
                userLog.UserName = "";
                userLog.FunctionId = DTO.FunctionId.人员关联角色;
                userLog.FunctionType = DTO.FunctionType.删除;
                InsertUserLog(content, objectid, userLog);
                #endregion

                result.Result = true;
                result.ReturnValue = null;
                result.Message = "删除成功！";
            }
            catch (Exception ex)
            {
                result.Message = "删除失败！" + ex.Message;
                result.Result = false;
            }
            return result;
        }

        public DTO.OperationResult AddRole(DTO.T_Sys_FuncPermission funcDTO)
        {

            return null;
        }

        #endregion

        #region 控件管理
        /// <summary>
        /// 获取控件列表
        /// </summary>
        /// <param name="title"></param>
        /// <param name="method"></param>
        /// <param name="clientlMethod"></param>
        /// <param name="description"></param>
        /// <returns></returns>
        public override List<DTO.T_Sys_Control> GetControls(string title, string method, string clientlMethod, string description)
        {
            var query = from a in dbContext.SysControl
                        where a.IsDel == false
                        select a;

            if (!string.IsNullOrEmpty(title))
            {
                query = query.Where(c => c.CtrlTitle.Contains(title));

            }
            if (!string.IsNullOrEmpty(method))
            {
                query = query.Where(c => c.CtrlMethod.Contains(method));
            }
            if (!string.IsNullOrEmpty(clientlMethod))
            {
                query = query.Where(c => c.CtrlClientlMethod.Contains(clientlMethod));
            }
            if (!string.IsNullOrEmpty(description))
            {
                query = query.Where(c => c.CtrlDescription.Contains(description));
            }
            List<DTO.T_Sys_Control> lists = new List<DTO.T_Sys_Control>();
            try
            {
                List<T_Sys_Control> list = query.OrderByDescending(c => c.IsrtDate).ToList();

                foreach (T_Sys_Control item in list)
                {
                    DTO.T_Sys_Control control = new DTO.T_Sys_Control();
                    EntityHelper.ConvertEntity2OtherEntity(item, control);
                    lists.Add(control);
                }
            }
            catch (Exception e)
            {

            }
            return lists;
        }

        /// <summary>
        /// 根据控件guid获取控件信息
        /// </summary>
        /// <param name="guid"></param>
        /// <returns></returns>
        public override DTO.T_Sys_Control GetControlByGuId(Guid guid)
        {
            T_Sys_Control control = dbContext.SysControl.Where(m => m.CtrlGuid == guid).FirstOrDefault();
            DTO.T_Sys_Control controls = new DTO.T_Sys_Control();
            EntityHelper.ConvertEntity2OtherEntity(control, controls);
            return controls;
        }
        /// <summary>
        /// 根据功能Guid获取该功能对应Control
        /// </summary>
        /// <param name="funguid"></param>
        /// <returns></returns>
        public override List<DTO.T_Sys_Control> GetControlByFunGuid(Guid funguid)
        {
            List<DTO.T_Sys_Control> controls = new List<DTO.T_Sys_Control>();
            try
            {
                List<T_Sys_Control> control = (from a in dbContext.SysControl
                                               where a.FuncGuid == funguid
                                               && a.IsDel == false
                                               select a).ToList();
                foreach (T_Sys_Control item in control)
                {
                    DTO.T_Sys_Control Dcontrol = new DTO.T_Sys_Control();
                    EntityHelper.ConvertEntity2OtherEntity(item, Dcontrol);
                    controls.Add(Dcontrol);
                }
            }
            catch
            {

            }
            return controls;
        }
        /// <summary>
        /// 添加控件
        /// </summary>
        /// <param name="controlDTO"></param>
        /// <returns></returns>
        public override DTO.OperationResult AddControl(DTO.T_Sys_Control controlDTO)
        {
            T_Sys_Control control = new T_Sys_Control();
            EntityHelper.ConvertEntity2OtherEntity(controlDTO, control);
            DTO.OperationResult result = new DTO.OperationResult();
            try
            {
                dbContext.SysControl.Add(control);
                dbContext.SaveChanges();

                #region 添加操作日志
                DTO.UserPermission userLog = new DTO.UserPermission();
                string content = "添加控件信息！";
                string objectid = control.ID.ToString();
                userLog.UserId = new Guid().ToString();
                userLog.UserName = "";
                userLog.FunctionId = DTO.FunctionId.控件模块;
                userLog.FunctionType = DTO.FunctionType.添加;
                InsertUserLog(content, objectid, userLog);
                #endregion

                result.Result = true;
                result.ReturnValue = null;
                result.Message = "添加成功！";
            }
            catch (Exception ex)
            {
                result.Message = "添加失败！" + ex.Message;
                result.Result = false;
            }
            return result;
        }

        /// <summary>
        /// 修改控件信息
        /// </summary>
        /// <param name="controlDTO"></param>
        /// <returns></returns>
        public override DTO.OperationResult UpdateControl(DTO.T_Sys_Control controlDTO)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            try
            {
                var control = dbContext.SysControl.Where(c => c.CtrlGuid == controlDTO.CtrlGuid).FirstOrDefault();
                if (control != null)
                {
                    control.FuncGuid = controlDTO.FuncGuid;
                    control.CtrlID = controlDTO.CtrlID;
                    control.CtrlTitle = controlDTO.CtrlTitle;
                    control.CtrlMethod = controlDTO.CtrlMethod;
                    control.CtrlClientlMethod = controlDTO.CtrlClientlMethod;
                    control.FuncType = controlDTO.FuncType;
                    control.CtrlDescription = controlDTO.CtrlDescription;
                    dbContext.SaveChanges();

                    #region 添加操作日志
                    DTO.UserPermission userLog = new DTO.UserPermission();
                    string content = "修改控件信息！";
                    string objectid = control.ID.ToString();
                    userLog.UserId = new Guid().ToString();
                    userLog.UserName = "";
                    userLog.FunctionId = DTO.FunctionId.控件模块;
                    userLog.FunctionType = DTO.FunctionType.修改;
                    InsertUserLog(content, objectid, userLog);
                    #endregion

                    result.Result = true;
                    result.ReturnValue = null;
                    result.Message = "修改成功！";
                }
            }
            catch (Exception ex)
            {
                result.Message = "修改失败！" + ex.Message;
                result.Result = false;
            }
            return result;
        }

        /// <summary>
        /// 删除控件
        /// </summary>
        /// <param name="controlGuid"></param>
        /// <returns></returns>
        public override DTO.OperationResult DeleteControl(string controlGuid)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            result.Result = false;
            try
            {
                Guid controlguid = Guid.Empty;
                Guid.TryParse(controlGuid, out controlguid);
                var control = dbContext.SysControl.Where(o => o.CtrlGuid == controlguid).FirstOrDefault();
                if (control != null)
                {
                    control.IsDel = true;
                    dbContext.SaveChanges();

                    #region 添加操作日志
                    DTO.UserPermission userLog = new DTO.UserPermission();
                    string content = "删除控件信息！(删除：设置IsDel字段为：false)";
                    string objectid = control.ID.ToString();
                    userLog.UserId = new Guid().ToString();
                    userLog.UserName = "";
                    userLog.FunctionId = DTO.FunctionId.控件模块;
                    userLog.FunctionType = DTO.FunctionType.删除;
                    InsertUserLog(content, objectid, userLog);
                    #endregion

                    result.Result = true;
                    result.ReturnValue = null;
                    result.Message = "删除成功！";
                }
            }
            catch (Exception ex)
            {
                result.Message = "删除失败！" + ex.Message;
            }
            return result;
        }

        /// <summary>
        /// 获取功能绑定下拉
        /// </summary>
        /// <returns></returns>
        public override List<DTO.GuidKeyAndValue> GetFunction()
        {
            List<DTO.GuidKeyAndValue> list = new List<DTO.GuidKeyAndValue>();
            var query =
                from a in dbContext.SysFunction
                select new DTO.GuidKeyAndValue { Key = a.FunctionGuid, Value = a.Title };
            list = query.ToList();
            return list;
        }
        #endregion

        /// <summary>
        /// 获取用户数量
        /// </summary>
        /// <param name="corpName"></param>
        /// <returns></returns>
        public override int GetUserCount(string corpName)
        {
            var query = from a in dbContext.T_Sys_Users
                        select a;

            if (!string.IsNullOrEmpty(corpName))
            {
                query = query.Where(r => r.DeptName.Contains(corpName));

            }
            int count = query.ToList().Count();
            return count;
        }

        /// <summary>
        /// 判断是否存在关联数据
        /// </summary>
        /// <param name="funcGuid">功能Guid/控件Guid</param>
        /// <param name="objGuid">角色或个人Guid</param>
        /// <param name="funcType">0：功能 1：控件</param>
        /// <param name="type">0：角色 1：个人</param>
        /// <returns></returns>
        public override DTO.OperationResult CheckPermission(string funcGuid, string objGuid, int funcType, int type, bool ischeck)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            try
            {
                var query = from a in dbContext.SysFuncPermission
                            select a;

                if (!string.IsNullOrEmpty(objGuid))
                {
                    query.Where(a => a.FunctionGuid == Guid.Parse(funcGuid));
                }
                if (!string.IsNullOrEmpty(funcGuid))
                {
                    query.Where(a => a.ObjectGuid == Guid.Parse(objGuid));
                }
                if (funcType > -1)
                {
                    query.Where(a => a.FuncType == funcType);
                }
                if (type > -1)
                {
                    query.Where(a => a.Type == type);
                }
                T_Sys_FuncPermission func = query.ToList().FirstOrDefault();
                if (func != null)
                {
                    if (func.IsDel != ischeck)
                    {
                        func.IsDel = ischeck;
                        dbContext.SaveChanges();
                    }
                    result.Result = true;
                    result.ReturnValue = 1;
                    result.Message = "操作成功！";
                }
                else
                {
                    result.Result = true;
                    result.ReturnValue = 0;
                    result.Message = "不存在数据！";
                }
            }
            catch (Exception ex)
            {
                result.Result = false;
                result.Message = "操作失败！";
            }
            return result;
        }

        #region 权限

        #region 菜单加载 wangxl
        private List<DTO.T_Sys_Function> GetUserFuncs(string userGuid, string functionGuid, string appId)
        {
            //加载用户所有菜单关系数据，集合中仅FunctionGuid有效
            List<DTO.T_Sys_FuncPermission> funcReList = this.GetFuncPermissionForUser(new Guid(userGuid), appId);
            //关联菜单功能信息返回
            var dbFunction = dbContext.SysFunction;
            List<T_Sys_Function> funList = dbFunction.ToList();
            var query = (from function in funList
                         join permission in funcReList on function.FunctionGuid equals permission.FunctionGuid
                         where function.IsDel == false
                         && function.AppID == appId
                         select new DTO.T_Sys_Function()
                         {
                             ID = function.ID,
                             FunctionGuid = function.FunctionGuid,
                             Code = function.Code,
                             Title = function.Title,
                             DESCRIPTION = function.DESCRIPTION,
                             ParenGuid = function.ParenGuid,
                             RootGuid = function.RootGuid,
                             Url = function.Url,
                             IsMenu = function.IsMenu,
                             AppID = function.AppID,
                             IsrtUseID = function.IsrtUseID,
                             IsrtDate = function.IsrtDate,
                             IsDel = function.IsDel,
                             SortIndex = function.SortIndex
                         }).ToList();
            return query;
        }

        #endregion

        /// <summary>
        /// 获取角色功能权限
        /// </summary>
        /// <param name="userGuid">人员guid</param>
        /// <param name="functionGuid">如果functionGuid不为null，就查找该人员角色下的所有功能，否则查找子功能</param>
        /// <param name="appId"></param>
        /// <returns></returns>
        private IQueryable<DTO.T_Sys_Function> GetUserRoleFuncs(string userGuid, string functionGuid, string appId)
        {
            var dbRole = dbContext.SysRoles;
            var dbFuncPermission = dbContext.SysFuncPermission;
            var dbFunction = dbContext.SysFunction;
            var dbUserRole = dbContext.SysUserRoles;
            Guid gUserGuid = Guid.Empty;
            Guid gFuncGuid = Guid.Empty;
            string functionCode = string.Empty;
            if (!string.IsNullOrEmpty(functionGuid) && !Guid.TryParse(functionGuid, out gFuncGuid))
            {
                functionCode = functionGuid;//code
            }
            if (Guid.TryParse(userGuid, out gUserGuid))
            {
                if (!string.IsNullOrEmpty(functionCode))//根据code查找子功能
                {
                    var query = from function in dbFunction
                                join func in dbFunction on function.ParenGuid equals func.FunctionGuid
                                join permission in dbFuncPermission on function.FunctionGuid equals permission.FunctionGuid
                                join role in dbRole on permission.ObjectGuid equals role.RoleGuid
                                join userRole in dbUserRole on role.RoleGuid equals userRole.RoleGuid
                                where userRole.UserGuid == gUserGuid
                                && func.Code == functionCode
                                && permission.Type == 0
                                && permission.FuncType == 0
                                && permission.IsDel == false
                                && function.IsDel == false
                                && role.IsDel == false
                                && userRole.IsDel == false
                                && func.AppID == appId
                                select new DTO.T_Sys_Function()
                                {
                                    ID = function.ID,
                                    FunctionGuid = function.FunctionGuid,
                                    Code = function.Code,
                                    Title = function.Title,
                                    DESCRIPTION = function.DESCRIPTION,
                                    ParenGuid = function.ParenGuid,
                                    RootGuid = function.RootGuid,
                                    Url = function.Url,
                                    IsMenu = function.IsMenu,
                                    AppID = function.AppID,
                                    IsrtUseID = function.IsrtUseID,
                                    IsrtDate = function.IsrtDate,
                                    IsDel = function.IsDel,
                                    SortIndex = function.SortIndex
                                };
                    return query;
                }
                else if (Guid.TryParse(functionGuid, out gFuncGuid))//根据functionguid查找子功能
                {
                    var query = from function in dbFunction
                                join permission in dbFuncPermission on function.FunctionGuid equals permission.FunctionGuid
                                join role in dbRole on permission.ObjectGuid equals role.RoleGuid
                                join userRole in dbUserRole on role.RoleGuid equals userRole.RoleGuid
                                where userRole.UserGuid == gUserGuid
                                && function.ParenGuid == gFuncGuid
                                && permission.Type == 0
                                && permission.FuncType == 0
                                && permission.IsDel == false
                                && function.IsDel == false
                                && role.IsDel == false
                                && userRole.IsDel == false
                                && function.AppID == appId
                                select new DTO.T_Sys_Function()
                                {
                                    ID = function.ID,
                                    FunctionGuid = function.FunctionGuid,
                                    Code = function.Code,
                                    Title = function.Title,
                                    DESCRIPTION = function.DESCRIPTION,
                                    ParenGuid = function.ParenGuid,
                                    RootGuid = function.RootGuid,
                                    Url = function.Url,
                                    IsMenu = function.IsMenu,
                                    AppID = function.AppID,
                                    IsrtUseID = function.IsrtUseID,
                                    IsrtDate = function.IsrtDate,
                                    IsDel = function.IsDel,
                                    SortIndex = function.SortIndex
                                };
                    return query;
                }
                else //查找所有功能
                {
                    var query = from function in dbFunction
                                join permission in dbFuncPermission on function.FunctionGuid equals permission.FunctionGuid
                                join role in dbRole on permission.ObjectGuid equals role.RoleGuid
                                join userRole in dbUserRole on role.RoleGuid equals userRole.RoleGuid
                                where userRole.UserGuid == gUserGuid
                                && permission.Type == 0
                                && permission.FuncType == 0
                                && permission.IsDel == false
                                && function.IsDel == false
                                && role.IsDel == false
                                && userRole.IsDel == false
                                && function.AppID == appId
                                select new DTO.T_Sys_Function()
                                {
                                    ID = function.ID,
                                    FunctionGuid = function.FunctionGuid,
                                    Code = function.Code,
                                    Title = function.Title,
                                    DESCRIPTION = function.DESCRIPTION,
                                    ParenGuid = function.ParenGuid,
                                    RootGuid = function.RootGuid,
                                    Url = function.Url,
                                    IsMenu = function.IsMenu,
                                    AppID = function.AppID,
                                    IsrtUseID = function.IsrtUseID,
                                    IsrtDate = function.IsrtDate,
                                    IsDel = function.IsDel,
                                    SortIndex = function.SortIndex
                                };
                    return query;
                }
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 查找用户是否有控件权限
        /// </summary>
        /// <param name="userGuid"></param>
        /// <param name="functionGuid"></param>
        /// <returns></returns>
        private IQueryable<DTO.T_Sys_Control> GetUserCtrls(string userGuid, string functionGuid, string appId)
        {
            Guid gUserGuid = Guid.Empty;
            Guid gFuncGuid = Guid.Empty;
            if (Guid.TryParse(userGuid, out gUserGuid) && Guid.TryParse(functionGuid, out gFuncGuid))
            {
                var dbFuncPermission = dbContext.SysFuncPermission;
                var dbControl = dbContext.SysControl;
                var query = from control in dbControl
                            join permission in dbFuncPermission on control.CtrlGuid equals permission.FunctionGuid
                            where permission.ObjectGuid == gUserGuid
                            && control.FuncGuid == gFuncGuid
                            && permission.Type == 1
                            && permission.FuncType == 1
                            && permission.IsDel == false
                            && control.IsDel == false
                            select new DTO.T_Sys_Control()
                            {
                                ID = control.ID,
                                CtrlGuid = control.CtrlGuid,
                                FuncGuid = control.FuncGuid,
                                CtrlID = control.CtrlID,
                                CtrlTitle = control.CtrlTitle,
                                CtrlMethod = control.CtrlMethod,
                                CtrlClientlMethod = control.CtrlClientlMethod,
                                FuncType = control.FuncType,
                                CtrlDescription = control.CtrlDescription,
                                IsrtUseID = control.IsrtUseID,
                                IsrtDate = control.IsrtDate,
                                IsDel = control.IsDel,
                                SortIndex = control.SortIndex
                            };
                return query;
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 查找用户功能权限下的控件
        /// </summary>
        /// <param name="userGuid"></param>
        /// <param name="functionGuid"></param>
        /// <returns></returns>
        private IQueryable<DTO.T_Sys_Control> GetCtrlsByUserFunc(string userGuid, string functionGuid, string appId)
        {
            Guid gUserGuid = Guid.Empty;
            Guid gFuncGuid = Guid.Empty;
            if (Guid.TryParse(userGuid, out gUserGuid) && Guid.TryParse(functionGuid, out gFuncGuid))
            {
                var dbFuncPermission = dbContext.SysFuncPermission;
                var dbControl = dbContext.SysControl;
                var dbFunction = dbContext.SysFunction;
                var query = from control in dbControl
                            join function in dbFunction on control.FuncGuid equals function.FunctionGuid
                            join permission in dbFuncPermission on function.FunctionGuid equals permission.FunctionGuid
                            where permission.ObjectGuid == gUserGuid
                            && function.FunctionGuid == gFuncGuid
                            && permission.Type == 1
                            && permission.FuncType == 0
                            && permission.IsDel == false
                            && function.IsDel == false
                            && control.IsDel == false
                            select new DTO.T_Sys_Control()
                            {
                                ID = control.ID,
                                CtrlGuid = control.CtrlGuid,
                                FuncGuid = control.FuncGuid,
                                CtrlID = control.CtrlID,
                                CtrlTitle = control.CtrlTitle,
                                CtrlMethod = control.CtrlMethod,
                                CtrlClientlMethod = control.CtrlClientlMethod,
                                FuncType = control.FuncType,
                                CtrlDescription = control.CtrlDescription,
                                IsrtUseID = control.IsrtUseID,
                                IsrtDate = control.IsrtDate,
                                IsDel = control.IsDel,
                                SortIndex = control.SortIndex
                            };
                return query;
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 查找角色下控件权限
        /// </summary>
        /// <param name="userGuid"></param>
        /// <param name="functionGuid"></param>
        /// <returns></returns>
        private IQueryable<DTO.T_Sys_Control> GetCtrlsByRoleCtrl(string userGuid, string functionGuid, string appId)
        {
            Guid gUserGuid = Guid.Empty;
            Guid gFuncGuid = Guid.Empty;
            if (Guid.TryParse(userGuid, out gUserGuid) && Guid.TryParse(functionGuid, out gFuncGuid))
            {
                var dbRole = dbContext.SysRoles;
                var dbFuncPermission = dbContext.SysFuncPermission;
                var dbControl = dbContext.SysControl;
                var dbUserRole = dbContext.SysUserRoles;
                var query = from control in dbControl
                            join permission in dbFuncPermission on control.CtrlGuid equals permission.FunctionGuid
                            join role in dbRole on permission.ObjectGuid equals role.RoleGuid
                            join userRole in dbUserRole on role.RoleGuid equals userRole.RoleGuid
                            where userRole.UserGuid == gUserGuid
                            && control.FuncGuid == gFuncGuid
                            && permission.Type == 0
                            && permission.FuncType == 1
                            && permission.IsDel == false
                            && control.IsDel == false
                            && role.IsDel == false
                            && userRole.IsDel == false
                            select new DTO.T_Sys_Control()
                            {
                                ID = control.ID,
                                CtrlGuid = control.CtrlGuid,
                                FuncGuid = control.FuncGuid,
                                CtrlID = control.CtrlID,
                                CtrlTitle = control.CtrlTitle,
                                CtrlMethod = control.CtrlMethod,
                                CtrlClientlMethod = control.CtrlClientlMethod,
                                FuncType = control.FuncType,
                                CtrlDescription = control.CtrlDescription,
                                IsrtUseID = control.IsrtUseID,
                                IsrtDate = control.IsrtDate,
                                IsDel = control.IsDel,
                                SortIndex = control.SortIndex
                            };
                return query;
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 查找角色功能权限下的控件
        /// </summary>
        /// <param name="userGuid"></param>
        /// <param name="functionGuid"></param>
        /// <returns></returns>
        private IQueryable<DTO.T_Sys_Control> GetCtrlsByRoleFunc(string userGuid, string functionGuid, string appId)
        {
            Guid gUserGuid = Guid.Empty;
            Guid gFuncGuid = Guid.Empty;
            if (Guid.TryParse(userGuid, out gUserGuid) && Guid.TryParse(functionGuid, out gFuncGuid))
            {
                var dbRole = dbContext.SysRoles;
                var dbFuncPermission = dbContext.SysFuncPermission;
                var dbControl = dbContext.SysControl;
                var dbUserRole = dbContext.SysUserRoles;
                var dbFunction = dbContext.SysFunction;
                var query = from control in dbControl
                            join function in dbFunction on control.FuncGuid equals function.FunctionGuid
                            join permission in dbFuncPermission on function.FunctionGuid equals permission.FunctionGuid
                            join role in dbRole on permission.ObjectGuid equals role.RoleGuid
                            join userRole in dbUserRole on role.RoleGuid equals userRole.RoleGuid
                            where userRole.UserGuid == gUserGuid
                            && function.FunctionGuid == gFuncGuid
                            && permission.Type == 0
                            && permission.FuncType == 0
                            && permission.IsDel == false
                            && function.IsDel == false
                            && control.IsDel == false
                            && role.IsDel == false
                            && userRole.IsDel == false
                            select new DTO.T_Sys_Control()
                            {
                                ID = control.ID,
                                CtrlGuid = control.CtrlGuid,
                                FuncGuid = control.FuncGuid,
                                CtrlID = control.CtrlID,
                                CtrlTitle = control.CtrlTitle,
                                CtrlMethod = control.CtrlMethod,
                                CtrlClientlMethod = control.CtrlClientlMethod,
                                FuncType = control.FuncType,
                                CtrlDescription = control.CtrlDescription,
                                IsrtUseID = control.IsrtUseID,
                                IsrtDate = control.IsrtDate,
                                IsDel = control.IsDel,
                                SortIndex = control.SortIndex
                            };
                return query;
            }
            else
            {
                return null;
            }
        }

        protected override List<DTO.T_Sys_Function> GetUserFunctionsInternal(string userGuid, string functionGuid, bool isMenu, string appId)
        {
            List<DTO.T_Sys_Function> result = new List<DTO.T_Sys_Function>();
            List<DTO.T_Sys_Function> query = GetUserFuncs(userGuid, functionGuid, appId);//获取用户功能
            if (query != null)
            {
                if (isMenu)
                {
                    query = query.Where(f => f.IsMenu == true).ToList();
                }
                result = query.Distinct().OrderBy(f => f.SortIndex).ToList();
                if (result.Count == 0)
                {
                    var query1 = GetUserRoleFuncs(userGuid, functionGuid, appId);//获取角色功能
                    if (query1 != null)
                    {
                        if (isMenu)
                        {
                            query1 = query1.Where(f => f.IsMenu == true);
                        }
                        result = query1.Distinct().OrderBy(f => f.SortIndex).ToList();
                    }
                }
            }
            return result;
        }

        /// <summary>
        /// 查询用户功能（所有功能，包括menu）
        /// </summary>
        /// <param name="userGuid"></param>
        /// <param name="functionGuid">可以是功能guid也可以是功能code，如果不传查询所有功能</param>
        /// <returns></returns>
        public override List<DTO.T_Sys_Function> GetUserFunctions(string userGuid, string functionGuid, string appId)
        {
            return GetUserFunctionsInternal(userGuid, functionGuid, false, appId);
        }

        /// <summary>
        /// 查询用户所属功能下的控件
        /// </summary>
        /// <param name="userGuid"></param>
        /// <param name="functionGuid">可以是功能guid也可以是功能code</param>
        /// <returns></returns>
        public override List<DTO.T_Sys_Control> GetUserControls(string userGuid, string functionGuid, string appId)
        {
            List<DTO.T_Sys_Control> result = new List<DTO.T_Sys_Control>();
            //判断用户是否有控件
            var query = GetUserCtrls(userGuid, functionGuid, appId);
            if (query != null)
            {
                result = query.Distinct().OrderBy(f => f.SortIndex).ToList();
                if (result.Count == 0)
                {
                    //判断用户是否有功能，获取用户功能下控件
                    var query1 = GetCtrlsByUserFunc(userGuid, functionGuid, appId);
                    if (query1 != null)
                    {
                        result = query1.Distinct().OrderBy(f => f.SortIndex).ToList();
                        if (result.Count == 0)
                        {
                            //判断角色是否有控件，获取角色下控件
                            var query2 = GetCtrlsByRoleCtrl(userGuid, functionGuid, appId);
                            if (query2 != null)
                            {
                                result = query2.Distinct().OrderBy(f => f.SortIndex).ToList();
                                if (result.Count == 0)
                                {
                                    //获取角色的功能，获取角色功能下控件
                                    var query3 = GetCtrlsByRoleFunc(userGuid, functionGuid, appId);
                                    if (query3 != null)
                                    {
                                        result = query3.Distinct().OrderBy(f => f.SortIndex).ToList();
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return result;
        }

        /// <summary>
        /// 查询功能菜单
        /// </summary>
        /// <param name="userGuid"></param>
        /// <param name="functionGuid">可以是功能guid也可以是功能code，不传查询所有菜单</param>
        /// <returns></returns>
        public override List<DTO.T_Sys_Function> GetUserMenus(string userGuid, string functionGuid, string appId)
        {
            return GetUserFunctionsInternal(userGuid, functionGuid, true, appId);
        }

        /// <summary>
        /// 获取用户功能code
        /// </summary>
        /// <param name="userGuid"></param>
        /// <param name="functionGuid"></param>
        /// <param name="isMenu"></param>
        /// <returns></returns>
        public override List<string> GetUserFuncCodes(string userGuid, bool isMenu, string appId)
        {
            List<string> result = new List<string>();
            var query = GetUserFuncs(userGuid, null, appId);
            if (query != null)
            {
                if (isMenu)
                {
                    query = query.Where(f => f.IsMenu == true).ToList();
                }

                result = query.Select(f => f.Code).Distinct().ToList();
                if (result.Count == 0)
                {
                    var query1 = GetUserRoleFuncs(userGuid, null, appId);
                    if (query1 != null)
                    {
                        if (isMenu)
                        {
                            query1 = query1.Where(f => f.IsMenu == true);
                        }
                        result = query1.Select(f => f.Code).Distinct().ToList();
                    }
                }
            }
            return result;
        }

        /// <summary>
        /// 获取角色下的功能
        /// </summary>
        /// <param name="roleGuid"></param>
        /// <param name="functionGuid">如果functionGuid不为null，就查找该角色下的所有功能，否则查找子功能</param>
        /// <param name="appId"></param>
        /// <returns></returns>
        private IQueryable<DTO.T_Sys_Function> GetRoleFunction(string roleGuid, string functionGuid, string appId)
        {
            var dbRole = dbContext.SysRoles;
            var dbFuncPermission = dbContext.SysFuncPermission;
            var dbFunction = dbContext.SysFunction;
            Guid gRoleGuid = Guid.Empty;
            Guid gFuncGuid = Guid.Empty;
            string functionCode = string.Empty;
            if (!string.IsNullOrEmpty(functionGuid) && !Guid.TryParse(functionGuid, out gFuncGuid))
            {
                functionCode = functionGuid;//code
            }
            if (Guid.TryParse(roleGuid, out gRoleGuid))
            {
                if (!string.IsNullOrEmpty(functionCode))//根据code查找子功能
                {
                    var query = from function in dbFunction
                                join func in dbFunction on function.ParenGuid equals func.FunctionGuid
                                join permission in dbFuncPermission on function.FunctionGuid equals permission.FunctionGuid
                                join role in dbRole on permission.ObjectGuid equals role.RoleGuid
                                where role.RoleGuid == gRoleGuid
                                && func.Code == functionCode
                                && permission.Type == 0
                                && permission.FuncType == 0
                                && permission.IsDel == false
                                && function.IsDel == false
                                && role.IsDel == false
                                && func.AppID == appId
                                select new DTO.T_Sys_Function()
                                {
                                    ID = function.ID,
                                    FunctionGuid = function.FunctionGuid,
                                    Code = function.Code,
                                    Title = function.Title,
                                    DESCRIPTION = function.DESCRIPTION,
                                    ParenGuid = function.ParenGuid,
                                    RootGuid = function.RootGuid,
                                    Url = function.Url,
                                    IsMenu = function.IsMenu,
                                    AppID = function.AppID,
                                    IsrtUseID = function.IsrtUseID,
                                    IsrtDate = function.IsrtDate,
                                    IsDel = function.IsDel,
                                    SortIndex = function.SortIndex
                                };
                    return query;
                }
                else if (Guid.TryParse(functionGuid, out gFuncGuid))//根据functionguid查找子功能
                {
                    var query = from function in dbFunction
                                join permission in dbFuncPermission on function.FunctionGuid equals permission.FunctionGuid
                                join role in dbRole on permission.ObjectGuid equals role.RoleGuid
                                where role.RoleGuid == gRoleGuid
                                && function.ParenGuid == gFuncGuid
                                && permission.Type == 0
                                && permission.FuncType == 0
                                && permission.IsDel == false
                                && function.IsDel == false
                                && role.IsDel == false
                                && function.AppID == appId
                                select new DTO.T_Sys_Function()
                                {
                                    ID = function.ID,
                                    FunctionGuid = function.FunctionGuid,
                                    Code = function.Code,
                                    Title = function.Title,
                                    DESCRIPTION = function.DESCRIPTION,
                                    ParenGuid = function.ParenGuid,
                                    RootGuid = function.RootGuid,
                                    Url = function.Url,
                                    IsMenu = function.IsMenu,
                                    AppID = function.AppID,
                                    IsrtUseID = function.IsrtUseID,
                                    IsrtDate = function.IsrtDate,
                                    IsDel = function.IsDel,
                                    SortIndex = function.SortIndex
                                };
                    return query;
                }
                else //查找所有功能
                {
                    var query = from function in dbFunction
                                join permission in dbFuncPermission on function.FunctionGuid equals permission.FunctionGuid
                                join role in dbRole on permission.ObjectGuid equals role.RoleGuid
                                where role.RoleGuid == gRoleGuid
                                && permission.Type == 0
                                && permission.FuncType == 0
                                && permission.IsDel == false
                                && function.IsDel == false
                                && role.IsDel == false
                                && function.AppID == appId
                                select new DTO.T_Sys_Function()
                                {
                                    ID = function.ID,
                                    FunctionGuid = function.FunctionGuid,
                                    Code = function.Code,
                                    Title = function.Title,
                                    DESCRIPTION = function.DESCRIPTION,
                                    ParenGuid = function.ParenGuid,
                                    RootGuid = function.RootGuid,
                                    Url = function.Url,
                                    IsMenu = function.IsMenu,
                                    AppID = function.AppID,
                                    IsrtUseID = function.IsrtUseID,
                                    IsrtDate = function.IsrtDate,
                                    IsDel = function.IsDel,
                                    SortIndex = function.SortIndex
                                };
                    return query;
                }
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 获取角色下的功能
        /// </summary>
        /// <param name="roleGuid"></param>
        /// <param name="functionGuid">可以是功能guid也可以是功能code</param>
        /// <param name="appId"></param>
        /// <returns></returns>
        public override List<DTO.T_Sys_Function> GetRoleFunctions(string roleGuid, string functionGuid, string appId)
        {
            List<DTO.T_Sys_Function> result = new List<DTO.T_Sys_Function>();
            var query1 = GetRoleFunction(roleGuid, functionGuid, appId);
            if (query1 != null)
            {
                result = query1.Distinct().OrderBy(f => f.SortIndex).ToList();
            }
            return result;
        }

        #region 菜单管理 wangxl edit by 20140312

        /// <summary>
        /// 获取单个用户获取权限信息
        /// </summary>
        /// <param name="userGuid"></param>
        /// <param name="appid"></param>
        /// <returns></returns>
        public override List<DTO.T_Sys_FuncPermission> GetFuncPermissionForUser(Guid userGuid, string appid)
        {
            Guid roleGuid = GetRoleGuidByUserGuid(userGuid);
            List<DTO.T_Sys_FuncPermission> lists = new List<DTO.T_Sys_FuncPermission>();
            List<Guid> rstList = new List<Guid>();
            List<Guid> listRole = new List<Guid>();
            List<Guid> listUserAdd = new List<Guid>();
            List<Guid> listUserDeduck = new List<Guid>();
            //获取该用户的全部权限关系包含个人和角色（未删除的）
            var query = from per in dbContext.SysFuncPermission
                        join func in dbContext.SysFunction on per.FunctionGuid equals func.FunctionGuid
                        where (per.ObjectGuid == roleGuid || per.ObjectGuid == userGuid) && func.AppID == appid && per.IsDel == false && func.IsDel == false
                        select per;
            var queryMenu = query.ToList();
            //获取该用户的角色权限关系和个人加的权限关系
            var queryAdd = queryMenu.Where(r => r.ObjectGuid == roleGuid || (r.ObjectGuid == userGuid && r.OperType == 0)).Select(r => r.FunctionGuid).Distinct().ToList();
            //获取该用户个人减的权限关系
            var queryUserDeduck = queryMenu.Where(r => r.ObjectGuid == userGuid && r.OperType == 1).Select(r => r.FunctionGuid).ToList();

            rstList.AddRange(queryAdd);
            rstList = rstList.Except(queryUserDeduck).ToList();

            DTO.T_Sys_FuncPermission en = null;
            foreach (Guid str in rstList)
            {
                en = new DTO.T_Sys_FuncPermission() { FunctionGuid = str };
                lists.Add(en);
            }
            return lists;
        }
        /// <summary>
        /// 给单个用户增加或修改权限
        /// </summary>
        public override bool SaveorUpdateFuncPermissionForUser(Guid userGuid, string appid, List<string> addFuncs)
        {
            Guid roleGuid = GetRoleGuidByUserGuid(userGuid);
            List<DTO.T_Sys_FuncPermission> lists = new List<DTO.T_Sys_FuncPermission>();

            List<Guid> listRole = new List<Guid>();
            List<Guid> listUserAdd = new List<Guid>();
            List<Guid> listUserDeduck = new List<Guid>();
            List<Guid> addGuidFuncs = new List<Guid>();

            foreach (string s in addFuncs)
            {
                addGuidFuncs.Add(Guid.Parse(s));
            }

            var queryMenu = (from per in dbContext.SysFuncPermission
                             join func in dbContext.SysFunction on per.FunctionGuid equals func.FunctionGuid
                             where (per.ObjectGuid == roleGuid || per.ObjectGuid == userGuid) && func.AppID == appid && per.IsDel == false && func.IsDel == false
                             select per).ToList();

            var queryRole = queryMenu.Where(r => r.ObjectGuid == roleGuid).Select(r => r.FunctionGuid).ToList();
            //获取该用户原增加的权限
            var queryUserAdd = queryMenu.Where(r => r.ObjectGuid == userGuid && (r.OperType == 0 || r.OperType == null)).Select(r => r.FunctionGuid).ToList();
            //获取该用户原减去的权限
            var queryUserDeduck = queryMenu.Where(r => r.ObjectGuid == userGuid && r.OperType == 1).Select(r => r.FunctionGuid).ToList();

            List<Guid> new_listUserAdd = new List<Guid>();
            List<Guid> new_listUserDeduck = new List<Guid>();
            //用户传来的 新权限关系 与该 角色的权限关系 作差集，获得新增关系和新减关系
            new_listUserAdd = addGuidFuncs.Except(queryRole).ToList();
            new_listUserDeduck = queryRole.Except(addGuidFuncs).ToList();

            try
            {
                //删除原来的增减菜单
                foreach (Guid g in queryUserAdd)
                {
                    DelFuncPermission(g, userGuid);
                }
                foreach (Guid g in queryUserDeduck)
                {
                    DelFuncPermission(g, userGuid);
                }

                //插入新的增减菜单
                foreach (Guid g in new_listUserAdd)
                {
                    AddFuncPermission(new DTO.T_Sys_FuncPermission
                    {
                        FunctionGuid = g,
                        ObjectGuid = userGuid,
                        IsDel = false,
                        IsrtDate = DateTime.Now,
                        Type = 1,  //个人 
                        FuncType = 0,
                        OperType = 0  //加                   
                    });
                }
                foreach (Guid g in new_listUserDeduck)
                {
                    AddFuncPermission(new DTO.T_Sys_FuncPermission
                    {
                        FunctionGuid = g,
                        ObjectGuid = userGuid,
                        IsDel = false,
                        IsrtDate = DateTime.Now,
                        Type = 1,  //个人 
                        FuncType = 0,
                        OperType = 1  //减                 
                    });
                }

            }
            catch (Exception ex)
            {
                return false;
            }

            return true;
        }

        /// <summary>
        /// 通过用户guid获取角色guid
        /// </summary>
        /// <param name="userGuid"></param>
        /// <returns></returns>
        private Guid GetRoleGuidByUserGuid(Guid userGuid)
        {
            string areacode = string.Empty;
            areacode = System.Configuration.ConfigurationManager.AppSettings["Area"];
            string roleID = string.Empty;
            Guid roleGuid = Guid.Empty;
            var user = dbContext.T_Sys_Users.Where(u => u.UserGuid == userGuid).FirstOrDefault();
            if (user != null)
            {
                if (string.IsNullOrEmpty(areacode))
                {
                    areacode = user.AreaCode.Substring(0, 2);
                }
                roleID = Convert.ToString(user.RoleID);
            }

            var role = dbContext.SysRoles.Where(r => r.Code == roleID && r.AreaCode == areacode).FirstOrDefault();
            if (role != null)
            {
                roleGuid = role.RoleGuid;
            }
            else
            {
                var userRole = dbContext.SysUserRoles.Where(u => u.UserGuid == userGuid).FirstOrDefault();
                if (userRole != null && userRole.RoleGuid != null)
                {
                    Guid.TryParse(userRole.RoleGuid.ToString(), out roleGuid);
                }
            }

            return roleGuid;
        }

        #endregion
        #endregion


        #region MyRegion
        public override List<DTO.T_Sys_Application> GetSysApp()
        {
            var query = from a in dbContext.SysApp
                        where a.IsDel == false
                        select a;
            List<T_Sys_Application> list = query.ToList();
            List<DTO.T_Sys_Application> lists = new List<DTO.T_Sys_Application>();
            foreach (T_Sys_Application item in list)
            {
                DTO.T_Sys_Application app = new DTO.T_Sys_Application();
                EntityHelper.ConvertEntity2OtherEntity(item, app);
                lists.Add(app);
            }

            return lists;
        }

        public override List<DTO.T_Sys_FuncPermission> GetUserSysPermission(string userGuid, int type)
        {
            Guid corpguid = Guid.Parse(userGuid);
            List<T_Sys_FuncPermission> list;
            list = dbContext.SysFuncPermission.Where(f => f.ObjectGuid == corpguid && f.Type == type).ToList();
            List<DTO.T_Sys_FuncPermission> lists = new List<DTO.T_Sys_FuncPermission>();
            foreach (T_Sys_FuncPermission item in list)
            {
                DTO.T_Sys_FuncPermission role = new DTO.T_Sys_FuncPermission();
                EntityHelper.ConvertEntity2OtherEntity(item, role);
                lists.Add(role);
            }
            return lists;
        }

        public override DTO.OperationResult UpdatePermission(DTO.T_Sys_FuncPermission funcDTO)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            try
            {
                var per = dbContext.SysFuncPermission.Where(p => p.FunctionGuid == funcDTO.FunctionGuid && p.ObjectGuid == funcDTO.ObjectGuid).FirstOrDefault();
                if (per != null)
                {
                    per.IsDel = funcDTO.IsDel;
                    dbContext.SaveChanges();

                    #region 添加操作日志
                    DTO.UserPermission userLog = new DTO.UserPermission();
                    string content = "变更权限isdel为" + funcDTO.IsDel.ToString();
                    string objectid = funcDTO.ID.ToString();
                    userLog.UserId = funcDTO.IsrtUseID != null ? funcDTO.IsrtUseID.ToString() : null;
                    userLog.UserName = "";
                    userLog.FunctionId = DTO.FunctionId.功能模块;
                    userLog.FunctionType = DTO.FunctionType.修改;
                    InsertUserLog(content, objectid, userLog);
                    #endregion

                    result.Result = true;
                    result.ReturnValue = null;
                    result.Message = "修改成功！";
                }
            }
            catch (Exception ex)
            {
                result.Message = "修改失败！" + ex.Message;
                result.Result = false;
            }

            return result;
        }

        #endregion

        /// <summary>
        /// 往T_Sys_FuncPageMapping表里插入数据，映射
        /// </summary>
        public override DTO.OperationResult AddPageMapping(DTO.FuncPageMapping page)
        {
            T_Sys_FuncPageMapping map = new T_Sys_FuncPageMapping();
            EntityHelper.ConvertEntity2OtherEntity(page, map);
            DTO.OperationResult result = new DTO.OperationResult();
            try
            {
                var query = dbContext.FuncPageMapping.Where(m => m.AppId == page.AppId && m.PageCode.ToLower() == page.PageCode.ToLower() && m.FuncCode.ToLower() == page.FuncCode.ToLower());
                if (query.Count() > 0)
                {
                    result.Message = "映射已存在！";
                    result.Result = false;
                }
                else
                {
                    dbContext.FuncPageMapping.Add(map);
                    dbContext.SaveChanges();
                    result.Result = true;
                    result.ReturnValue = null;
                    result.Message = "添加成功！";
                }
            }
            catch (Exception ex)
            {
                result.Message = "添加失败！" + ex.Message;
                result.Result = false;
            }
            return result;
        }


        #region 部门管理
        /// <summary>
        /// 获取dict_Department中的数据 
        /// </summary>
        /// <param name="AreaCode"></param>
        /// <returns></returns>
        public override List<dict_Department> GetDepartmentData(string AreaCode)
        {
            var query = from d in dbContext.DictDepartment
                        where d.SysAreaCode == AreaCode
                        select d;
            if (!string.IsNullOrEmpty(AreaCode))
            {
                query = query.Where(r => r.AreaCode.Contains(AreaCode));
            }
            List<dict_Department> lists = query.OrderBy(m => m.OrderNum).ToList();

            return lists;
        }

        /// <summary>
        /// 添加部门
        /// </summary>
        /// <param name="role"></param>
        /// <returns></returns>
        public override DTO.OperationResult AddDepartment(DTO.dict_Department dept)
        {
            dict_Department deptE = new dict_Department();
            EntityHelper.ConvertEntity2OtherEntity(dept, deptE);

            DTO.OperationResult result = new DTO.OperationResult();
            try
            {
                dbContext.DictDepartment.Add(deptE);
                dbContext.SaveChanges();

                result.Result = true;
                result.ReturnValue = null;
                result.Message = "部门添加成功！";
            }
            catch (Exception ex)
            {
                result.Message = "部门添加失败！" + ex.Message;
                result.Result = false;
            }
            return result;
        }

        /// <summary>
        /// 修改部门
        /// </summary>
        /// <param name="roleDTO"></param>
        /// <returns></returns>
        public override DTO.OperationResult UpdateDepartment(DTO.dict_Department dept)
        {
            
            DTO.OperationResult result = new DTO.OperationResult();
            result.Result = false;
            try
            {
                var deptE = dbContext.DictDepartment.Where(r => r.ID == dept.ID).FirstOrDefault();

                if (deptE != null)
                {
                    deptE.DeptID = dept.DeptID;
                    deptE.DepartName = dept.DepartName;
                    deptE.AreaCode = dept.AreaCode;
                    deptE.OrderNum = dept.OrderNum;
                    deptE.isStatistic = dept.isStatistic;
                    dbContext.SaveChanges();

                    result.Result = true;
                    result.ReturnValue = null;
                    result.Message = "部门修改成功！";
                }
            }
            catch (Exception ex)
            {
                result.Message = "部门修改失败！" + ex.Message;
            }
            return result;
        }

        /// <summary>
        /// 删除部门
        /// </summary>
        /// <param name="roleGuid"></param>
        /// <returns></returns>
        public override DTO.OperationResult DeleteDepartment(int id)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            result.Result = false;
            try
            {
                var deptE = dbContext.DictDepartment.Where(r => r.ID == id).FirstOrDefault();
                if (deptE != null)
                {
                    dbContext.DictDepartment.Remove(deptE);
                    dbContext.SaveChanges();

                    result.Result = true;
                    result.ReturnValue = null;
                    result.Message = "删除成功！";
                }
            }
            catch (Exception ex)
            {
                result.Message = "删除失败！" + ex.Message;
            }
            return result;
        }

        #endregion

    }
}
